package org.oaix.img;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;

public class ImgBase64Utils {

    /**
     * 图片base64转文件
     * @param base64
     * @return
     */
    public static File imgBase64ToFile(String base64) {
        if (StringUtils.isBlank(base64)) {
            return null;
        }
        try {
            return Files.write(Files.createTempFile(UUID.randomUUID().toString(),"."+base64Suffix(base64)), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE).toFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片base64转文件，回调后删除
     * @param base64
     * @return
     */
    public static void imgBase64CallFile(String base64,Function<File,Object> call) {
        File file = null;
        try {
            file = imgBase64ToFile(base64);
            call.apply(file);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(file)){
                file.delete();
            }
        }
    }

    private static String base64Suffix(String base64Str) {
        base64Str = StringUtils.trim(base64Str);
        if (StringUtils.isBlank(base64Str)) {
            return "";
        }
        //+号字符转成空格引起图片损坏问题
        base64Str=base64Str.replace(" ","+");
        String type = "", suffix = "jpg";
        InputStream inputStream = null;
        try {
            if (!isBase64Image(base64Str)){
                return "";
            }
            if (!base64Str.contains("base64,")) {
                inputStream = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(base64Str));
                type = HttpURLConnection.guessContentTypeFromStream(new BufferedInputStream(inputStream));
                type = type == null ? "" : type;
                switch (type) {
                    case "image/jpeg":
                        suffix = "jpeg";
                        break;
                    case "image/png":
                        suffix = "png";
                        break;
                    case "image/gif":
                        suffix = "gif";
                        break;
                    default:
                        suffix = "jpg";
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return suffix;
    }

    //判断base64是否可以转换图片
    private static boolean isBase64Image(String imgBase64Str){
        if (StringUtils.isBlank(imgBase64Str)) {
            return false;
        } else {
            ByteArrayInputStream byteArrayInputStream = null;
            try {
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] byteArray = decoder.decodeBuffer(imgBase64Str);
                byteArrayInputStream = new ByteArrayInputStream(byteArray);
                BufferedImage bufImg = ImageIO.read(byteArrayInputStream);
                if (bufImg == null) {
                    return false;
                }
                bufImg = null;
            }catch (Exception e){
                return false;
            }finally {
                if (byteArrayInputStream != null) {
                    try {
                        byteArrayInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return true;
    }
}
